<template>
	<view class="container">
		<u-form :model="form" ref="uForm" label-width="200">
			<u-form-item label="姓名" prop="name" required>
				<u-input v-model="form.name" placeholder="请输入姓名" />
			</u-form-item>

			<u-form-item label="身份证号码" prop="id_card" required>
				<u-input v-model="form.id_card" placeholder="请输入18位身份证号码" />
			</u-form-item>

			<u-form-item label="性别" prop="gender" required>
				<u-radio-group v-model="form.gender">
					<u-radio name="男">男</u-radio>
					<u-radio name="女">女</u-radio>
				</u-radio-group>
			</u-form-item>

			<u-form-item label="联系电话" prop="phone" required>
				<u-input v-model="form.phone" placeholder="请输入联系电话" />
			</u-form-item>

			<u-form-item label="毕业时间" prop="graduation_date" required>
				<u-input v-model="form.graduation_date" placeholder="请选择毕业时间" readonly
					@click="showGraduationCalendar = true" />
			</u-form-item>

			<u-form-item label="毕业院校" prop="school" required>
				<u-input v-model="form.school" placeholder="请输入毕业院校" />
			</u-form-item>

			<u-form-item label="专业" prop="major" required>
				<u-input v-model="form.major" placeholder="请输入专业" />
			</u-form-item>

			<u-form-item label="学历" prop="education" required>
				<u-input v-model="form.education" placeholder="请选择学历" readonly @click="showEducationSelect = true" />
			</u-form-item>

			<u-form-item label="面试时间" prop="interview_date" required>
				<u-input v-model="form.interview_date" placeholder="请选择面试时间" readonly
					@click="showInterviewCalendar = true" />
			</u-form-item>

			<u-form-item label="面试企业名称" prop="company_name" required>
				<u-input v-model="form.company_name" placeholder="请输入面试企业名称" />
			</u-form-item>

			<u-form-item label="常住地址" prop="address" required>
				<u-input v-model="form.address" placeholder="请输入常住地址" />
			</u-form-item>

			<u-form-item label="银行账号" prop="bank_account" required>
				<u-input v-model="form.bank_account" placeholder="请输入银行账号" />
			</u-form-item>

			<u-form-item label="开户行及网点" prop="bank_name" required>
				<u-input v-model="form.bank_name" placeholder="请输入开户行及网点" />
			</u-form-item>

			<u-form-item label="身份证正面照片" prop="id_card_front_photo" required>
				<view class="upload-section">
					<view class="upload-list">
						<view v-for="(image, index) in uploadedImages.front" :key="index" class="upload-item">
							<image :src="image" mode="aspectFill" class="upload-image" />
							<view class="delete-btn" @click="deleteImage('front', index)">×</view>
						</view>
					</view>
					<u-button v-if="uploadedImages.front.length < 6" @click="chooseImage('front')" type="primary"
						size="mini">
						上传图片
					</u-button>
				</view>
			</u-form-item>

			<u-form-item label="身份证反面照片" prop="id_card_back_photo" required>
				<view class="upload-section">
					<view class="upload-list">
						<view v-for="(image, index) in uploadedImages.back" :key="index" class="upload-item">
							<image :src="image" mode="aspectFill" class="upload-image" />
							<view class="delete-btn" @click="deleteImage('back', index)">×</view>
						</view>
					</view>
					<u-button v-if="uploadedImages.back.length < 6" @click="chooseImage('back')" type="primary"
						size="mini">
						上传图片
					</u-button>
				</view>
			</u-form-item>

			<u-form-item label="毕业证书或教育部学历证书电子注册备案表" prop="graduation_cert_photo" required>
				<view class="upload-section">
					<view class="upload-list">
						<view v-for="(image, index) in uploadedImages.graduation" :key="index" class="upload-item">
							<image :src="image" mode="aspectFill" class="upload-image" />
							<view class="delete-btn" @click="deleteImage('graduation', index)">×</view>
						</view>
					</view>
					<u-button v-if="uploadedImages.graduation.length < 6" @click="chooseImage('graduation')"
						type="primary" size="mini">
						上传图片
					</u-button>
				</view>
			</u-form-item>

			<u-form-item label="学位证照片" prop="degree_cert_photo">
				<view class="upload-section">
					<view class="upload-list">
						<view v-for="(image, index) in uploadedImages.degree" :key="index" class="upload-item">
							<image :src="image" mode="aspectFill" class="upload-image" />
							<view class="delete-btn" @click="deleteImage('degree', index)">×</view>
						</view>
					</view>
					<u-button v-if="uploadedImages.degree.length < 6" @click="chooseImage('degree')" type="primary"
						size="mini">
						上传图片
					</u-button>
				</view>
			</u-form-item>

			<u-form-item label="在企业求职面试现场照片" prop="invitation_material_photo" required>
				<view class="upload-section">
					<view class="upload-list">
						<view v-for="(image, index) in uploadedImages.invitation" :key="index" class="upload-item">
							<image :src="image" mode="aspectFill" class="upload-image" />
							<view class="delete-btn" @click="deleteImage('invitation', index)">×</view>
						</view>
					</view>
					<u-button v-if="uploadedImages.invitation.length < 6" @click="chooseImage('invitation')"
						type="primary" size="mini">
						上传图片
					</u-button>
				</view>
			</u-form-item>
		</u-form>

		<!-- 毕业时间日历 -->
		<u-calendar v-model="showGraduationCalendar" mode="date" @change="onGraduationDateChange"></u-calendar>

		<!-- 面试时间日历 -->
		<u-calendar v-model="showInterviewCalendar" mode="date" @change="onInterviewDateChange"></u-calendar>

		<!-- 学历选择器 -->
		<u-select v-model="showEducationSelect" mode="single-column" :list="educationList"
			@confirm="onEducationConfirm"></u-select>

		<!-- 底部固定提交按钮 -->
		<view class="submit-section">
			<u-button type="primary" @click="submitForm" :loading="submitting">提交申请</u-button>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			form: { "name": "", "id_card": "", "gender": "", "phone": "", "graduation_date": "", "school": "", "major": "", "education": "", "interview_date": "", "company_name": "", "address": "", "bank_name": "", "bank_account": "", "id_card_front_photo": "", "id_card_back_photo": "", "graduation_cert_photo": "", "degree_cert_photo": "", "invitation_material_photo": "", "front_photo": "", "back_photo": "", "graduation_photo": "", "invitation_photo": "" },
			uploadedImages: {
				front: [],
				back: [],
				graduation: [],
				degree: [],
				invitation: []
			},
			rules: {
				name: [{
					required: true,
					message: '请输入姓名',
					trigger: ['blur', 'change']
				}],
				id_card: [{
					required: true,
					message: '请输入身份证号码',
					trigger: ['blur', 'change']
				}],
				gender: [{
					required: true,
					message: '请选择性别',
					trigger: ['blur', 'change']
				}],
				phone: [{
					required: true,
					message: '请输入联系电话',
					trigger: ['blur', 'change']
				}],
				graduation_date: [{
					required: true,
					message: '请选择毕业时间',
					trigger: ['blur', 'change']
				}],
				school: [{
					required: true,
					message: '请输入毕业院校',
					trigger: ['blur', 'change']
				}],
				major: [{
					required: true,
					message: '请输入专业',
					trigger: ['blur', 'change']
				}],
				education: [{
					required: true,
					message: '请选择学历',
					trigger: ['blur', 'change']
				}],
				interview_date: [{
					required: true,
					message: '请选择面试时间',
					trigger: ['blur', 'change']
				}],
				company_name: [{
					required: true,
					message: '请输入面试企业名称',
					trigger: ['blur', 'change']
				}],
				address: [{
					required: true,
					message: '请输入常住地址',
					trigger: ['blur', 'change']
				}],
				bank_name: [{
					required: true,
					message: '请输入开户行及网点',
					trigger: ['blur', 'change']
				}],
				bank_account: [{
					required: true,
					message: '请输入银行账号',
					trigger: ['blur', 'change']
				}]
			},
			showGraduationCalendar: false,
			showInterviewCalendar: false,
			showEducationSelect: false,
			educationList: [
				{ label: '高中', value: '高中' },
				{ label: '中专', value: '中专' },
				{ label: '大专', value: '大专' },
				{ label: '本科', value: '本科' },
				{ label: '硕士', value: '硕士' },
				{ label: '博士', value: '博士' }
			],
			currentUploadType: '',
			submitting: false
		}
	},
	methods: {
		// 毕业时间选择确认
		onGraduationDateChange(e) {
			this.form.graduation_date = e.result;
			this.showGraduationCalendar = false;
		},

		// 面试时间选择确认
		onInterviewDateChange(e) {
			this.form.interview_date = e.result;
			this.showInterviewCalendar = false;
		},

		// 学历选择确认
		onEducationConfirm(e) {
			this.form.education = e[0].value;
			this.showEducationSelect = false;
		},

		// 选择图片
		chooseImage(type) {
			this.currentUploadType = type;
			if (this.uploadedImages[type].length >= 6) {
				uni.showToast({
					title: '最多只能上传6张图片',
					icon: 'none'
				});
				return;
			}

			uni.chooseImage({
				count: 6 - this.uploadedImages[type].length,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					this.uploadImages(res.tempFilePaths);
				},
				fail: (err) => {
					console.log('选择图片失败', err);
				}
			});
		},

		// 上传图片
		uploadImages(filePaths) {
			uni.showLoading({
				title: '上传中...'
			});

			const uploadPromises = filePaths.map(filePath => {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: this.$api.uploadImage,
						filePath: filePath,
						name: 'file',
						success: (uploadFileRes) => {
							try {
								let data = JSON.parse(uploadFileRes.data);
								const url = data.data.url;
								resolve(url);
								uni.showToast({
									title: '上传成功',
									icon: 'success'
								});
							} catch (error) {
								reject(error);
							}
						},
						fail: (err) => {
							console.log('上传失败', err);
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							});
							reject(err);
						},
						complete: () => {
							uni.hideLoading();
						}
					});
				});
			});

			Promise.all(uploadPromises)
				.then(urls => {
					this.uploadedImages[this.currentUploadType] = [...this.uploadedImages[this.currentUploadType], ...urls];
					// 更新表单数据
					this.form[`${this.currentUploadType}_photo`] = this.uploadedImages[this.currentUploadType].join(',');
				})
				.catch(error => {
					console.log('批量上传失败', error);
				});
		},

		// 删除图片
		deleteImage(type, index) {
			this.uploadedImages[type].splice(index, 1);
			// 更新表单数据
			this.form[`${type}_photo`] = this.uploadedImages[type].join(',');
		},

		// 提交表单
		async submitForm() {
			try {
				// 表单验证
				const valid = await this.$refs.uForm.validate();
				console.log(valid);
				if (!valid) {
					return;
				}

				// 检查必填图片
				if (!this.uploadedImages.front || this.uploadedImages.front.length === 0) {
					uni.showToast({
						title: '请上传身份证正面照片',
						icon: 'none'
					});
					return;
				}
				if (!this.uploadedImages.back || this.uploadedImages.back.length === 0) {
					uni.showToast({
						title: '请上传身份证反面照片',
						icon: 'none'
					});
					return;
				}
				if (!this.uploadedImages.graduation || this.uploadedImages.graduation.length === 0) {
					uni.showToast({
						title: '请上传毕业证书或教育部学历证书电子注册备案表',
						icon: 'none'
					});
					return;
				}
				if (!this.uploadedImages.invitation || this.uploadedImages.invitation.length === 0) {
					uni.showToast({
						title: '请上传在企业求职面试现场照片',
						icon: 'none'
					});
					return;
				}

				// 显示加载提示
				uni.showLoading({
					title: '提交中...'
				});

				// 准备提交数据，将图片数组转换为逗号分隔的字符串
				const submitData = {
					...this.form,
					id_card_front_photo: this.uploadedImages.front.join(','),
					id_card_back_photo: this.uploadedImages.back.join(','),
					graduation_cert_photo: this.uploadedImages.graduation.join(','),
					degree_cert_photo: this.uploadedImages.degree ? this.uploadedImages.degree.join(',') : '',
					invitation_material_photo: this.uploadedImages.invitation.join(',')
				};

				// 调用创建API
				await this.$api.jobSubsidyCreate(submitData);

				uni.hideLoading();
				uni.showToast({
					title: '提交成功',
					icon: 'success'
				});

				// 重置表单
				this.$refs.uForm.resetFields();
				this.uploadedImages = {
					front: [],
					back: [],
					graduation: [],
					degree: [],
					invitation: []
				};

				// 延迟返回上一页
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			} catch (error) {
				console.log(error);
			}
		}
	},
	// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
	onReady() {
		this.$refs.uForm.setRules(this.rules);
	}
}
</script>

<style lang="scss" scoped>
.container {
	padding: 40rpx;
	padding-bottom: 120rpx;
	background-color: #fff;
	min-height: 100vh;
}

.upload-section {
	margin-top: 10rpx;
}

.upload-list {
	display: flex;
	flex-wrap: wrap;
	gap: 20rpx;
	margin-bottom: 20rpx;
}

.upload-item {
	position: relative;
	width: 120rpx;
	height: 120rpx;
}

.upload-image {
	width: 100%;
	height: 100%;
	border-radius: 8rpx;
}

.delete-btn {
	position: absolute;
	top: -10rpx;
	right: -10rpx;
	width: 40rpx;
	height: 40rpx;
	background-color: #ff4444;
	color: white;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 24rpx;
	font-weight: bold;
}

.submit-section {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #fff;
	padding: 20rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
	z-index: 999;
}
</style>
